<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input id="input" type="file" />
    <script>
      const ele = document.getElementById("input");
      ele.onchange = (e) => {
        console.log(e.target.files[0]);
        function calculateAverageHash(imgSrc, callback) {
          const canvas = document.createElement("canvas");
          const ctx = canvas.getContext("2d");
          const img = new Image();
          img.crossOrigin = "Anonymous"; // 处理跨域问题
          img.onload = function () {
            const width = 8;
            const height = 8;
            canvas.width = width;
            canvas.height = height;
            ctx.drawImage(img, 0, 0, width, height);
            const data = ctx.getImageData(0, 0, width, height).data;
            let avg = 0;
            for (let i = 0; i < data.length; i += 4) {
              avg += (data[i] + data[i + 1] + data[i + 2]) / 3;
            }
            avg = avg / (width * height);
            let hash = "";
            for (let i = 0; i < data.length; i += 4) {
              hash +=
                (data[i] + data[i + 1] + data[i + 2]) / 3 < avg ? "0" : "1";
            }
            callback(hash);
          };
          img.src = imgSrc;
        }

        const url = URL.createObjectURL(e.target.files[0]);
        console.log("url:", url);
        // 使用示例
        calculateAverageHash(url, function (hash) {
          console.log("Image hash:", hash);
        });
      };
    </script>
  </body>
</html>
